package com.codi.api.xxljob;

import com.codi.base.util.ListUtil;
import com.codi.bus.constant.CacheKeyConst;
import com.codi.bus.constant.GlobalConstant;
import com.codi.bus.core.domain.FundInfo;
import com.codi.bus.core.service.FundDetailService;
import com.codi.bus.core.service.FundInfoService;
import com.codi.bus.core.util.JobUtil;
import com.codi.fundData.domain.FundDetail;
import com.codi.fundData.service.FundCodeRelationshipService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author lvgo
 * @version 1.0
 * @Description: 刷新基金编码关联
 * MF_CodeRelationshipNew
 * 0 10 2 ? * *
 * @date 18-6-29 下午4:43
 */
@Slf4j
@Component
@JobHandler("fundCodeRelationalship")
public class FundCodeRelationalshipHandler extends IJobHandler {
    @Autowired
    private FundInfoService fundInfoService;

    @Autowired
    private FundDetailService fundDetailService;

    @Autowired
    private FundCodeRelationshipService fundCodeRelationshipService;

    @Override
    public ReturnT<String> execute(String s) throws Exception {
        log.info("Fund Code Relational ship job");

        updateCache();
        JobUtil.updateJobExecuteTime(CacheKeyConst.MF_FUND_CODE_RELATIONSHIP_NEW);
        XxlJobLogger.log("FundCodeRelationalship-JOB, success");

        return SUCCESS;
    }


    private void updateCache() {

        int pageIndex = 1;

        while (true) {
            log.debug("loading fund pageIndex={}", pageIndex);

            List<FundInfo> funds = fundInfoService.queryPage(GlobalConstant.PAGE_SIZE, pageIndex);
            if (ListUtil.isNotEmpty(funds)) {
                for (FundInfo fund : funds) {
                    FundDetail detail = fundDetailService.getFundDetail(fund.getFundCode());
                    if (detail != null) {
                        fundCodeRelationshipService.refreshCodeRelationshipCache(detail.getInnerCode());
                    }
                }
                if (funds.size() < GlobalConstant.PAGE_SIZE) {
                    break;
                }
            } else {
                break;
            }

            pageIndex++;
        }
    }
}
